package logicals

import (
	"easyblog/models"
	"easyblog/utils/db"
	"easyblog/utils/errmsg"
	"gorm.io/gorm"
)

type DefaultFriendLinkLogical struct {}

var DefaultFriendLink = DefaultFriendLinkLogical{}

/**
* CreateFriendLink
* @Description: 新建链接
* @receiver this
* @param friendlink
* @return int
*/
func (this *DefaultFriendLinkLogical) CreateFriendLink(friendlink *models.FriendLink) int {
	err := db.Db.Create(friendlink).Error
	if err != nil {
		return errmsg.ERROR
	}
	return errmsg.SUCCSE
}

/**
* EditCategory
* @Description: 编辑链接
* @receiver this
* @param friendlinkId
* @param friendlink
* @return int
*/
func (this *DefaultFriendLinkLogical) EditFriendLink(friendlinkId int, friendlink *models.FriendLink) int {
	var maps = make(map[string]interface{})
	maps["name"] = friendlink.Name
	maps["url"] = friendlink.Url

	err := db.Db.Model(&models.FriendLink{}).Where("id = ?", friendlinkId).Updates(maps).Error
	if err != nil {
		return errmsg.ERROR
	}
	return errmsg.SUCCSE
}

/**
* DeleteFriendLink
* @Description: 删除链接
* @receiver this
* @param friendlinkId
* @return int
*/
func (this *DefaultFriendLinkLogical) DeleteFriendLink(friendlinkId int) int {
	err := db.Db.Where("id = ?", friendlinkId).Delete(&models.FriendLink{}).Error
	if err != nil {
		return errmsg.ERROR
	}
	return errmsg.SUCCSE
}

/**
* GetFriendLinkById
* @Description: 通过id获取链接
* @receiver this
* @param friendlinkId
* @return models.FriendLink
* @return int
*/
func (this *DefaultFriendLinkLogical) GetFriendLinkById(friendlinkId int) (models.FriendLink, int) {
	var friendlink models.FriendLink
	err := db.Db.Where("id = ?", friendlinkId).First(&friendlink).Error
	if err != nil {
		return friendlink,errmsg.ERROR
	}
	return friendlink,errmsg.SUCCSE
}

/**
* GetPageFriendLinks
* @Description: 分页查询链接
* @receiver this
* @param pageSize
* @param pageNum
* @return []models.FriendLink
* @return int64
*/
func (this *DefaultFriendLinkLogical) GetPageFriendLinks(pageSize int, pageNum int) ([]models.FriendLink, int64) {
	var friendlinks []models.FriendLink
	var total int64

	err := db.Db.Find(&friendlinks).Limit(pageSize).Offset(pageSize * (pageNum - 1)).Error
	db.Db.Model(&friendlinks).Count(&total)
	// 不存在
	if err != nil && gorm.ErrRecordNotFound != nil {
		return nil, 0
	}
	return friendlinks, total
}

/**
* GetHotFriendLinks
* @Description: 获得前5个链接
* @receiver this
* @return []models.FriendLink
* @return int
*/
func (this *DefaultFriendLinkLogical) GetHotFriendLinks() ([]models.FriendLink, int) {
	var friendlinks []models.FriendLink
	err := db.Db.Find(&friendlinks).Limit(5).Error

	if err != nil && gorm.ErrRecordNotFound != nil {
		return nil, errmsg.ERROR
	}
	return friendlinks, errmsg.SUCCSE
}